package com.fatcat.easybuy.interceptor;

import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fatcat.easybuy.annotaion.CheckPermission;
import com.fatcat.easybuy.exception.LoginException;
import com.fatcat.easybuy.pojo.EasyBuyUser;
import com.fatcat.easybuy.service.EasyBuyUserService;
import com.fatcat.easybuy.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author 郝秦毅
 * @since 2025/9/12 14:06
 */
@Component
public class UserCheckInterceptor implements HandlerInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserCheckInterceptor.class);
    @Autowired
    private EasyBuyUserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOGGER.info("请求地址：" + request.getRequestURI());
        String token = request.getHeader("Authorization");//获取token
        LOGGER.info("token:" + token);
        //验证token是否登录
        if (token == null || token.equals("")) {
            // 没有登录
            throw new LoginException("401", "未登录");

        }

        //验证token
        Long userID = null;
        try {
            userID = JwtUtil.getUserId(token);
        } catch (SignatureVerificationException e) {
            throw new LoginException("401", "验签错误");
        } catch (TokenExpiredException e) {
            throw new LoginException("401", "登录超时");
        }
        String serverToken = redisTemplate.opsForValue().get(userID.toString());
        if (serverToken == null || !token.equals(serverToken)) {
            throw new LoginException("401", "验签错误");
        }
        if (userID == null) {
            throw new LoginException("401", "用户ID解析失败");
        }
        request.setAttribute("userId", userID);

        //Token延期
        Date tokenExpireDate;
        try {
            tokenExpireDate = JwtUtil.getExpireTime(token);
        } catch (Exception e) {
            throw new LoginException("401", "token格式错误");
        }
        if (tokenExpireDate.getTime() - System.currentTimeMillis() <= 5 * 60 * 1000) {
            // 延期
            String newToken = JwtUtil.createToken(userID);
            redisTemplate.opsForValue().set(userID.toString(), newToken, 30, TimeUnit.MINUTES);
            response.setHeader("Access-Control-Expose-Headers", "x-token");
            response.setHeader("x-token", newToken);
        }

        //权限验证
        boolean isHandlerMethod = handler instanceof HandlerMethod;
        if (!isHandlerMethod) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        CheckPermission checkPermission = handlerMethod.getMethodAnnotation(CheckPermission.class);
        if (checkPermission == null) {
//			throw new RuntimeException("无权限");
            return true;
        }
        String[] roles = checkPermission.value();
        LOGGER.info("角色：" + Arrays.toString(roles));
        if (checkRole(userID, roles)) {
            return true;
        } else {
            throw new LoginException("403", "权限不足");
        }
    }

    public boolean checkRole(long userID, String[] roles) {
        EasyBuyUser user = userService.getUserById(userID);
        for (String role : roles) {
            if (role.equals(user.getType().toString())) {
                return true;
            }
        }
        return false;
    }
}
